import { Device } from "@/api/interface/iot";
import { getAlarmList } from "@/api/modules/iot/alarm";
import { getDevice } from "@/api/modules/iot/device";
// import geoJsonData from "@/assets/json/china_geojson.json";
import { MAP_KEY } from "@/config/config";
import { RouterPath } from "@/enums/routerPath";
import { getDictInfo } from "@/utils/cacheUtil";
import mittBus from "@/utils/mittBus";
import { gotoPage } from "@/utils/routerUtil";
// import { LineLayer, PointLayer, PolygonLayer, Popup, Scene } from "@antv/l7";
import { Popup, Scene, PointLayer } from "@antv/l7";
import { GaodeMap } from "@antv/l7-maps";
let defaultLocatin = {
	address: "湖北省武汉市江夏区关东街道华中科技大学科技园创新基地9栋",
	lat: 30.443124,
	lng: 114.402748
};
export default defineComponent({
	emits: [],
	setup(props, { expose }) {
		const height = 0;
		onMounted(() => {
			initMap();
			mittBus.on("gotoMap", (info: any) => {
				if (!info.sn) {
					return;
				}
				let cacheDev;
				getDevice({ idSn: info.sn }).then(({ result, code }) => {
					if (code == 200 && result) {
						cacheDev = stat.deviceList.find(item => item.info.sn == result.sn);
						if (!cacheDev) {
							//添加一个新设备
							cacheDev = {
								sn: info.sn,
								name: info.sn,
								location: defaultLocatin
							};
							stat.deviceList.push({ ...defaultLocatin, info: cacheDev });
						} else if (!cacheDev.location?.lng || !cacheDev.location?.lat) {
							//添加默认位置
							cacheDev.location = defaultLocatin;
						} else {
							//使用设备最新信息
							cacheDev = { ...result };
						}
					} else {
						//设备不存在
						cacheDev = stat.deviceList.find(item => item.info.sn == info.sn);
						if (!cacheDev) {
							//追加加个设备
							cacheDev = {
								sn: info.sn,
								name: info.sn,
								location: defaultLocatin
							};
							stat.deviceList.push({ ...defaultLocatin, info: cacheDev });
						} else {
							//设置默认位置
							cacheDev.sn = info.sn;
							cacheDev.name = info.sn;
							cacheDev.location = defaultLocatin;
						}
					}
					stat.layer.setData(stat.deviceList);
					stat.alarmLayer.setData(stat.deviceList);
					showPopup(cacheDev);
					stat.scene.setCenter([cacheDev.location.lng, cacheDev.location.lat]);
				});
			});
		});
		const stat = reactive({
			scene: {} as Scene,
			popup: "" as any,
			layer: {} as any,
			alarmLayer: {} as any,
			deviceList: [] as any[]
		});
		const initMap = () => {
			stat.scene = new Scene({
				id: "map",
				logoVisible: false,
				antialias: false,
				map: new GaodeMap({
					viewMode: "3D",
					style: "amap://styles/673523d33c4fc24da22c9e199626c02a?isPublic=true",
					center: [15.008252, 30.878629],
					zoom: 0,
					pitch: 10,
					token: MAP_KEY
				})
			});
			stat.scene.on("loaded", () => {
				// let data = geoJsonData;
				// //区域边框
				// let lineUp = new LineLayer({ zIndex: 1 }).source(data).shape("line").color("#d7e4ed").size(1).style({
				// 	raisingHeight: height
				// });
				// stat.scene.addLayer(lineUp);
				// //栅栏
				// const lineLayer = new LineLayer()
				// 	.source(data)
				// 	.shape("wall")
				// 	.size(height + 30000)
				// 	.style({
				// 		heightfixed: true,
				// 		opacity: 1,
				// 		sourceColor: "#90b6d2",
				// 		targetColor: "#90b6d2"
				// 	});
				// stat.scene.addLayer(lineLayer);
				// const provincelayer = new PolygonLayer({})
				// 	.source(data)
				// 	.size(1)
				// 	.shape("fill")
				// 	.color("#fff")
				// 	.active({
				// 		color: "#f0f5fa"
				// 	})
				// 	.style({ raisingHeight: height, heightfixed: true, pickLight: true, opacity: 1 });
				// stat.scene.addLayer(provincelayer);
			});
		};
		const showPopup = async (info: Device.ResDeviceInfo) => {
			initPopup(info.alarmStatus);
			let popupHtml = await getPopupHtml(info);
			// 更新 Popup
			stat.popup
				.setLngLat({
					lng: info.location.lng,
					lat: info.location.lat
				})
				.setHTML(popupHtml);
			stat.popup.show();
			document.querySelector(".goto-sn")?.addEventListener("click", function () {
				let sn = document.querySelector(".goto-sn")?.getAttribute("sn");
				if (sn) gotoPage(RouterPath.deviceDetail, { sn: sn });
			});
		};
		const getPopupHtml = async (info: Device.ResDeviceInfo): Promise<string> => {
			if (info.alarmStatus) {
				let { result } = await getAlarmList({ sn: info.sn, pageIndex: 1, pageSize: 1 });
				let alarmInfo = result.records?.[0] || {};

				let dict = await getDictInfo("warning_level", alarmInfo.level);
				return `
				<div class="device-alarm-popup flex">
					<div class="type">${dict?.label || "设备告警"}</div>
					<div class="data flex-1">
					<div class="label">${info.name || info.sn}</div>
					<div class="info">${alarmInfo.alarmType}</div>
					<div class="tips">${alarmInfo.alarmTime}</div>
					</div
				</div>
				`;
			} else {
				return `<div class="device-popup">
				<div class="flex item-row">
				<div class="data-header">设备基本信息</div>
				</div>
				${
					info.sn
						? `<div class="flex item-row">
								<div class="label">设备SN:</div>
								<div class="value">${info.sn}（<span class="goto-sn link" class="link" sn="${info.sn}">详情</span>）</div>
							</div>`
						: ""
				}
				${
					info.name
						? `<div class="flex item-row">
								<div class="label">设备名称:</div>
								<div class="value">${info.name}</div>
							</div>`
						: ""
				}
				${
					info.deptName
						? `<div class="flex item-row">
								<div class="label">所属分组:</div>
								<div class="value">${info.deptName}</div>
							</div>`
						: ""
				}
				${
					info.gatewaySn
						? `<div class="flex item-row">
								<div class="label">接入网关:</div>
								<div class="value">${info.gatewaySn}</div>
							</div>`
						: ""
				}
				${
					info.productModel
						? `<div class="flex item-row">
								<div class="label">产品编码:</div>
								<div class="value">${info.productModel}</div>
							</div>`
						: ""
				}
				${
					info.updateTime
						? `<div class="flex item-row">
								<div class="label">更新时间:</div>
								<div class="value">${info.updateTime}</div>
							</div>`
						: ""
				}
				<div class="flex item-row">
					<div class="label">经度:</div>
					<div class="value">${info.location?.lng}</div>
				</div>
				<div class="flex item-row">
				<div class="label">纬度:</div>
					<div class="value">${info.location?.lat}</div>
				</div>
				<div class="flex item-row">
				<div class="label">详细位置:</div>
					<div class="value">${info.location?.address}</div>
				</div>
				</div>`;
			}
		};
		const initPopup = (isAlarm: boolean) => {
			stat.popup = new Popup({
				// 初始锚点经纬度
				lngLat: {
					lng: 120,
					lat: 30
				},
				maxWidth: "500px",
				closeButton: false,
				closeOnClick: true,
				closeOnEsc: true,
				autoPan: false,
				title: "",
				html: isAlarm ? "" : "设备详情"
			});
			stat.scene.addPopup(stat.popup);
		};
		const load = (res: any) => {
			if (!stat.scene.map) {
				setTimeout(() => {
					load(res);
				}, 1500);
				return;
			}
			let result = res.result;
			let data: any[] = [];
			let deviceTotal = { total: 0, online: 0, offline: 0 };
			result.records.forEach((item: Device.ResDeviceInfo) => {
				if (item.onlineStatus == "online") {
					deviceTotal.online += 1;
				} else {
					deviceTotal.offline += 1;
				}
				if (item.location?.lat && item.location?.lng) {
					data.push({ lat: item.location.lat, lng: item.location.lng, info: item });
				}
			});
			stat.deviceList = data;
			deviceTotal.total = deviceTotal.online + deviceTotal.offline;
			mittBus.emit("deviceTotal", deviceTotal);

			stat.layer = new PointLayer({ autoFit: false })
				.source(stat.deviceList, {
					parser: {
						type: "json",
						x: "lng",
						y: "lat"
					}
				})
				// .filter("info", (val: any) => {
				// 	return !val.alarmStatus;
				// })
				.shape("info", (val: any) => {
					if (val.productModel == "ssiot-applet-sysinfo") {
						return "hexagram";
					} else {
						return "circle";
					}
				})
				.size("info", (val: any) => {
					if (val.productModel == "ssiot-applet-sysinfo") {
						return 5;
					} else {
						return 4;
					}
				})
				.active(true)
				.color("info", (val: any) => {
					if (val.alarmStatus) {
						return "red";
					} else if (val.onlineStatus == "online") {
						return "green";
					} else {
						return "#555555";
					}
				})
				.style({ raisingHeight: height, heightfixed: true, pickLight: true, opacity: 1 });
			stat.scene.addLayer(stat.layer);
			// mapContent.scene.fitBounds([[lnglat.lng, lnglat.lat]]);
			stat.layer.on("click", (e: any) => {
				showPopup(e.feature.info);
			});

			stat.alarmLayer = new PointLayer({})
				.source(stat.deviceList, {
					parser: {
						type: "json",
						x: "lng",
						y: "lat"
					}
				})
				.filter("info", (val: any) => {
					return val.alarmStatus;
				})
				.shape("circle")
				.size(25)
				.active(true)
				.animate(true)
				.color("red")
				.style({ raisingHeight: height, heightfixed: true, pickLight: true, opacity: 1 });
			stat.scene.addLayer(stat.alarmLayer);
			stat.alarmLayer.on("click", (e: any) => {
				showPopup(e.feature.info);
			});
			// pointLayer.on("unclick", (e: any) => {
			// 	if (e.target.target?.className == "amap-layer") {
			// 		stat.popup && stat.popup.hide();
			// 	}
			// });
		};
		expose({ load });
		return () => {
			return (
				<div style="" class="layout-map">
					<div class="map-panel">
						<div class="linear-gradient top-linear-gradient"></div>
						<div class="linear-gradient left-linear-gradient"></div>
						<div class="linear-gradient right-linear-gradient"></div>
						<div class="linear-gradient bottom-linear-gradient"></div>
						<div style="justify-content: center;overflow: hidden;" id="map" />
					</div>
				</div>
			);
		};
	}
});
